<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use app\admin\model\pt\JobPlan as PlanModel;
use app\admin\model\pt\Job as JobModel;
use app\admin\model\pt\Depart as DepartModel;
use app\admin\model\pt\DutyList as DutyModel;
use app\admin\model\pt\Salary as SalaryModel;
use Carbon\Carbon;
use think\Db;

/**
 * 报表统计
 *
 * @icon fa fa-circle-o
 */
class Statistic extends Backend
{

    /**
     * LaborStatistic模型对象
     * @var \app\admin\model\pt\LaborStatistic
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        // $this->model = model('AdminLog');
    }

    public function index()
    {
        $monthId = date('Ym');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $monthId = date('Ym', strtotime($this->request->get('query_date') . "-01"));

            $resDepart = $this->feeDepartStatistic($monthId);
            $resType = $this->feeTypeStatistic($monthId);
            
            $result = ['depart' => $resDepart[1], 'type' => $resType[1]];    

            $this->success('获取成功', '', $result);
        } else {
            $resDepart = $this->feeDepartStatistic($monthId);
            $resType = $this->feeTypeStatistic($monthId);
        }
        $this->view->assign('total', $resDepart[0]);
        $this->view->assign('feeDepart', json_encode($resDepart[1]));
        $this->view->assign('feeUserType', json_encode($resType[1]));
        $this->view->assign('query_date', date('Y-m'));
        return $this->view->fetch();
    }

    public function duty()
    {
        $monthId = date('Ym');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $monthId = date('Ym', strtotime($this->request->get('query_date') . "-01"));

            $resDepart = $this->dutyDepartStatistic($monthId);
            $resType = $this->dutyTypeStatistic($monthId);
            
            $result = ['depart' => $resDepart[1], 'type' => $resType[1]];    

            $this->success('获取成功', '', $result);
        } else {
            $resDepart = $this->dutyDepartStatistic($monthId);
            $resType = $this->dutyTypeStatistic($monthId);
        }
        $this->view->assign('total', $resDepart[0]);
        $this->view->assign('feeDepart', json_encode($resDepart[1]));
        $this->view->assign('feeUserType', json_encode($resType[1]));
        $this->view->assign('query_date', date('Y-m'));
        return $this->view->fetch();
    }

    private function feeDepartStatistic($monthId)
    {
        $curMonthCarbon = Carbon::parse($monthId . "01");
        
        $startDay = $curMonthCarbon->firstOfMonth()->toDateString();
        $lastDay = $curMonthCarbon->lastOfMonth()->toDateString();
        $startDateId = date('Ymd', strtotime($startDay));
        $endDateId = date('Ymd', strtotime($lastDay));

        $allDeparts = DepartModel::where('status', 'normal')->select();
        $departIds = [];
        $departs = [];
        foreach ($allDeparts as $d) {
            $departs[$d->id] = $d->name;
            $departIds[] = $d->id;
        }
        // 查出总费用
        $list = Db::name('pt_person_salary')
          ->where('date_id', '>=', $startDateId)
          ->where('date_id', '<=', $endDateId)
          ->where('is_cal', 1)
          ->where('pt_depart_id', 'in', $departIds)->field('pt_depart_id, sum(salary_total) as total_salary')->group('pt_depart_id')->select();
        $total = 0;
        $feeDepart = [];
        $depart = [];
        $data = [];
        foreach ($list as $l) {
            if (isset($departs[$l['pt_depart_id']])) {
                $depart[] = $departs[$l['pt_depart_id']];
            } else {
                $depart[] = '未知部门';
            }
            $data[] = $l['total_salary'];
            $total += $l['total_salary'];
        }
        $feeDepart['depart'] = $depart;
        $feeDepart['data'] = $data;

        return [$total, $feeDepart];
    
    }

    private function feeTypeStatistic($monthId)
    {
        $curMonthCarbon = Carbon::parse($monthId . "01");
        
        $startDay = $curMonthCarbon->firstOfMonth()->toDateString();
        $lastDay = $curMonthCarbon->lastOfMonth()->toDateString();
        $startDateId = date('Ymd', strtotime($startDay));
        $endDateId = date('Ymd', strtotime($lastDay));

        $allDeparts = DepartModel::where('status', 'normal')->select();
        $departIds = [];
        $departs = [];
        foreach ($allDeparts as $d) {
          $departs[$d->id] = [
              'name' => $d->name,
              'intern' => 0,
              'part_time' => 0,
          ];
          $departIds[] = $d->id;
        }
        // 查出总费用
        $list = SalaryModel::where('pt_depart_id', 'in', $departIds)
          ->where('date_id', '>=', $startDateId)
          ->where('date_id', '<=', $endDateId)
          ->where('is_cal', 1)
          ->with('person')
          ->select();
        $total = 0;
        $feeDepart = [];

        foreach ($list as $l) {
            if (isset($departs[$l['pt_depart_id']])) {
                if ($l['person']['user_type'] == 'intern') {
                    $departs[$l['pt_depart_id']]['intern'] += $l['salary_total'];
                } else {
                    $departs[$l['pt_depart_id']]['part_time'] += $l['salary_total'];
                }
                $total += $l['salary_total'];
            }
        }
        $type = ['兼职', '实习生'];
        $depart = [];
        $intern = []; 
        $partTime = [];
        foreach ($departs as $d) {
            $depart[] = $d['name']; 
            $intern[] = $d['intern'];
            $partTime[] = $d['part_time'];
        }
        $feeDepart['depart'] = $depart;
        $feeDepart['type'] = $type;
        $feeDepart['intern'] = $intern;
        $feeDepart['part_time'] = $partTime;

        return [$total, $feeDepart];
    
    }

    private function dutyDepartStatistic($monthId)
    {
        $curMonthCarbon = Carbon::parse($monthId . "01");
        
        $startDay = $curMonthCarbon->firstOfMonth()->toDateString();
        $lastDay = $curMonthCarbon->lastOfMonth()->toDateString();
        $startDateId = date('Ymd', strtotime($startDay));
        $endDateId = date('Ymd', strtotime($lastDay));

        $allDeparts = DepartModel::where('status', 'normal')->select();
        $departIds = [];
        $departs = [];
        foreach ($allDeparts as $d) {
            $departs[$d->id] = $d->name;
            $departIds[] = $d->id;
        }
        // 查出总费用
        $list = Db::name('pt_person_salary')
          ->where('date_id', '>=', $startDateId)
          ->where('date_id', '<=', $endDateId)
          ->where('actual_duration', '>', 0)
          ->where('pt_depart_id', 'in', $departIds)->field('pt_depart_id, count(id) as total_duty')->group('pt_depart_id')->select();
        $total = 0;
        $feeDepart = [];
        $depart = [];
        $data = [];
        foreach ($list as $l) {
            if (isset($departs[$l['pt_depart_id']])) {
                $depart[] = $departs[$l['pt_depart_id']];
            } else {
                $depart[] = '未知部门';
            }
            $data[] = $l['total_duty'];
            $total += $l['total_duty'];
        }
        $feeDepart['depart'] = $depart;
        $feeDepart['data'] = $data;

        return [$total, $feeDepart];
    
    }

    private function dutyTypeStatistic($monthId)
    {
        $curMonthCarbon = Carbon::parse($monthId . "01");
        
        $startDay = $curMonthCarbon->firstOfMonth()->toDateString();
        $lastDay = $curMonthCarbon->lastOfMonth()->toDateString();
        $startDateId = date('Ymd', strtotime($startDay));
        $endDateId = date('Ymd', strtotime($lastDay));

        $allDeparts = DepartModel::where('status', 'normal')->select();
        $departIds = [];
        $departs = [];
        foreach ($allDeparts as $d) {
          $departs[$d->id] = [
              'name' => $d->name,
              'intern' => 0,
              'part_time' => 0,
          ];
          $departIds[] = $d->id;
        }
        // 查出总费用
        $list = SalaryModel::where('pt_depart_id', 'in', $departIds)
          ->where('date_id', '>=', $startDateId)
          ->where('date_id', '<=', $endDateId)
          ->where('actual_duration', '>', 0)
          ->with('person')
          ->select();
        $total = 0;
        $feeDepart = [];

        foreach ($list as $l) {
            if (isset($departs[$l['pt_depart_id']])) {
                if ($l['person']['user_type'] == 'intern') {
                    $departs[$l['pt_depart_id']]['intern']++;
                } else {
                    $departs[$l['pt_depart_id']]['part_time']++;
                }
                $total++;
            }
        }
        $type = ['兼职', '实习生'];
        $depart = [];
        $intern = []; 
        $partTime = [];
        foreach ($departs as $d) {
            $depart[] = $d['name']; 
            $intern[] = $d['intern'];
            $partTime[] = $d['part_time'];
        }
        $feeDepart['depart'] = $depart;
        $feeDepart['type'] = $type;
        $feeDepart['intern'] = $intern;
        $feeDepart['part_time'] = $partTime;

        return [$total, $feeDepart];
    
    }

}
